import React, { Component } from 'react';
import { connect } from 'dva';
import {Button,Form,Select,Input,message,Cascader} from 'antd';
import './less/report.less';
import Drawer from 'react-motion-drawer';

import { getDictInformation,getDistrictData,saveOrgShareholder,comStockGetShareholderById } from "../../../services/api";
import PSelect from "../../../components/Pro/PSelect";
const FormItem = Form.Item;
const { TextArea } = Input;
const {Option} = Select;
let addShareolderIdLocal = '';


@connect(state => ({profile: state.profile}))
@Form.create()

export default class AddShareholder extends Component {
  constructor(props,context){
    super(props,context);
    this.state = {
      // comId:1, //默认企业为1
      openAddShareolder:this.props.visiable,//新增机构股东
      addShareolderId:0,
      initUpd:0,
      init:0,
      initAdd:0,
      addShareolderList:{
        comType:'',//公司类型
        name:'',//公司名称
        comCerType:'',//证件类型
        cerNo:'',//证件号码
        // province:'',//省
        // city:'',//市
        // area:'',//区
        areas:[], //省市区
        address:'',//具体地址
      }
    };
  }

  componentWillReceiveProps(props){
    if(props.visiable){
      this.setState({openAddShareolder:props.visiable});
      this.setState({addShareolderId:props.addShareolderId},()=>{
        if(this.state.addShareolderId !== 0 && this.state.addShareolderId !== undefined){
          // console.log("进入机构股东修改");
          if(addShareolderIdLocal !== props.idx){ //编辑时，输入任何数据都会重复的执行，用此方法保证不会重复执行
            comStockGetShareholderById({id:this.state.addShareolderId}).then((data)=>{
              data.data.areas = [data.data.province, data.data.city, data.data.area];
              // console.log('编辑',data.data);
              this.setState({
                addShareolderList:{
                  comType: data.data.comType,//公司类型
                  name: data.data.name,//公司名称
                  comCerType: data.data.comCerType,//证件类型
                  cerNo:data.data.cerNo,//证件号码
                  // province:'',//省
                  // city:'',//市
                  // area:'',//区
                  areas:data.data.areas, //省市区
                  address:data.data.address,//具体地址
                }
              });
              console.log('编辑',this.state.addShareolderList);
              this.props.form.setFieldsValue(this.state.addShareolderList);
            });
            addShareolderIdLocal = props.idx;
          }
        }else{
          if(this.state.initAdd === 0){
            console.log("进入机构股东新增");
            this.props.form.setFieldsValue({
                comType:'',//公司类型
                name:'',//公司名称
                comCerType:'',//证件类型
                cerNo:'',//证件号码
                // province:'',//省
                // city:'',//市
                // area:'',//区
                areas:[],
                address:'',//具体地址
            });
            this.setState({ initAdd:1});
          }
          console.log("");
        }
      });
    }
  }

  handleSubmitShareolder = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if(!err){

        values.province = values.areas[0];
        values.city = values.areas[1];
        values.area = values.areas[2];
        // values.comId = this.state.comId;
        if (this.state.addShareolderId !== 0) {
          values.shareholderId = this.state.addShareolderId;
        }
        console.log('提交的内容：',values);
        this.setState({ loading: true});
        saveOrgShareholder({...values}).then((data) => {
          // message.success('提交成功！');
          console.log('this',this);
          this.props.forceUpdate();
          this.setState({
            openAddShareolder:false,
            loading:false
          });
          if (this.state.addShareolderId === 0) {
            this.setState({ initAdd:0});
          }
        });
        delete values.areas;
      }
    });
  };

  componentDidMount() {
    this.getDistrict();
  }

  //省市区
  getDistrict = () => {
    getDistrictData().then((data) => {
      console.log('省市区data:', data);
      let areas = data.data.map((val) => {
          return {
            value: val.regionId,
            label: val.regionName,
            children:val.childs.map((valChild) => {
              return {
                value: valChild.regionId,
                label: valChild.regionName,
                children:valChild.childs.map((valChildChild) => {
                  return {
                    value: valChildChild.regionId,
                    label: valChildChild.regionName,
                  }
                })
              }
            })
          };
        }
      );
      //console.log('areas:'+JSON.stringify(areas));
      this.setState({
        areas: areas,
      });
    })
  };


  //验证名称类，限制不能全角输入
  checkFullWidth = (rule, value, callback) => {
    if (value && !(/^[a-zA-Z\u4e00-\u9fa5]+$/).test(value)) {
      callback('请输入最大20个字符长度的名称！');
    } else {
      callback();
    }
  };

  render() {
    const formItemLayout = {
      labelCol: {
        xs: {span: 24},
        sm: {span: 7},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 12},
        md: {span: 10},
      },
    };
    let mark = '新增';
    if(this.state.addShareolderId !== 0 && this.state.addShareolderId !== undefined){
      mark = '修改';
    }

    const {getFieldDecorator} = this.props.form;
    // console.log(">>>>>>>>>>>>>>>>",this.state.addShareolderList);
     return(
       <Drawer
         overlayColor="rgba(0, 0, 0,0)"
         right
         open={this.state.openAddShareolder}
         noTouchClose
         width={600}
         zIndex={2}
         className="drawer-box"
         onChange={(openAddShareolder) => {
           this.props.onChange(openAddShareolder);
           this.setState({openAddShareolder});
         }}
       >
         <div className="drawer">
           <div className="drawer-header">
             <h3>{mark}机构股东</h3>
           </div>
           <div className="drawer-content" style={{marginTop:24}}>
             <Form onSubmit={this.handleSubmitShareolder}>
               <FormItem
                 {...formItemLayout}
                 label="企业类型"
               >
                 {getFieldDecorator('comType', {
                   initialValue: this.state.addShareolderList.comType,
                   rules: [
                     { required: true, message: '请选择企业类型!' },
                   ],
                 })(
                  <PSelect type="comType" style={{width: '100%'}}/>
                 )}
               </FormItem>
               <FormItem
                 {...formItemLayout}
                 label="名称"
               >
                 {getFieldDecorator('name', {
                   initialValue: this.state.addShareolderList.name,
                   rules: [{
                     required: true, message: '请输入名称',
                   }, {
                    validator: this.checkFullWidth
                  }],
                 })(
                   <Input placeholder="请输入" maxLength="20"/>
                 )}
               </FormItem>
               <FormItem
                 {...formItemLayout}
                 label="证件类型"
                 hasFeedback
               >
                 {getFieldDecorator('comCerType', {
                   initialValue: this.state.addShareolderList.comCerType,
                   rules: [
                     { required: true, message: '请选择证件类型!' },
                   ],
                 })(
                    <PSelect type="comCerType" style={{width: '100%'}}/>
                 )}
               </FormItem>
               <FormItem
                 {...formItemLayout}
                 label="证件号码"
               >
                 {getFieldDecorator('cerNo', {
                   initialValue: this.state.addShareolderList.cerNo,
                   rules: [{
                    pattern: /^[A-Za-z0-9]{1,20}$/, message: '请输最大20个字母数字!',
                  },{
                     required: true, message: '请填写证件号码',
                   }],
                 })(
                   <Input placeholder="请填写证件号码" maxLength="20"/>
                 )}
               </FormItem>
               <FormItem
                 {...formItemLayout}
                 label="注册地址"
                 hasFeedback
               >
                 {getFieldDecorator('areas', {
                  //  initialValue: [this.state.addShareolderList.province,this.state.addShareolderList.city,this.state.addShareolderList.area],
                  initialValue: this.state.addShareolderList.areas,
                  rules: [
                     { required: true, message: '请选择注册地址!' },
                   ],
                 })(
                  <Cascader options={this.state.areas} placeholder="请选择" />
                 )}
               </FormItem>
               <FormItem
                 {...formItemLayout}
                 label=" "
                 colon={false}
                 className="wed-none"
               >
                 {getFieldDecorator('address', {
                   initialValue: this.state.addShareolderList.address,
                   rules: [{
                     required: true, message: '请填写公司注册详细地址',
                   }],
                 })(
                    <TextArea rows={8} placeholder="请填写公司注册详细地址" maxLength="100"/>
                 )}
               </FormItem>
             </Form>
           </div>
           <div className="drawer-footer">
             <Button onClick={()=>{
               this.setState({openAddShareolder:false});
               if (this.state.addShareolderId === 0) {
                this.setState({ initAdd:0});
               }
             }}>取消</Button>
             <Button type="primary" htmlType="submit" onClick={this.handleSubmitShareolder} loading={this.state.loading}>保存</Button>
           </div>
         </div>
       </Drawer>
     );
  }
}

